<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <h2>vue2事件总线(event bus)</h2>
      <child1></child1>
      <child2></child2>
    </div>

    <script src="./lib/vue2.js"></script>
    <script>
      const bus = new Vue();

      // this.$on()
      // this.$emit()
      // this.$off()

      const Child1 = {
        data() {
          return {
            count: 10,
          };
        },
        template: `
          <div>
            <div>这是child1子组件</div>
            <button @click="handleClick">btn</button>
          </div>
        `,
        methods: {
          handleClick() {
            bus.$emit("change", this.count);
          },
        },
      };

      const Child2 = {
        template: `
          <div>这是child2子组件</div>
        `,
        mounted() {
          bus.$on("change", (v) => {
            console.log(v);
          });
        },
        beforeDestroy() {
          bus.$off("change");
        },
      };

      new Vue({
        data() {
          return {};
        },
        components: {
          Child1,
          Child2,
        },
      }).$mount("#app");
    </script>
  </body>
</html>
